package com.xish.api.activity;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xish.model.bean.WzmActivity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.IOException;

@Repository
public class ActivityRedisDao {

    private static final Logger LOG = LoggerFactory.getLogger(ActivityRedisDao.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("#{envFactory.get('activity.cachePrefix') ?: 'activity'}")
    private String cachePrefix;

    public String getCachePrefix() {
        return cachePrefix;
    }

    public WzmActivity findById(final int id) {
        String key = getCacheKey(id);
        String value = redisTemplate.opsForValue().get(key);
        LOG.debug("read: key={}, value={}", key, value);

        if ((value == null) || value.isEmpty()) {
            return null;
        }

        try {
            return objectMapper.readValue(value, WzmActivity.class);
        } catch (IOException e) {
            LOG.warn("Invalid WzmActivity json content: {}", value);
            return null;
        }
    }

    public void save(WzmActivity activity) {
        if (activity != null) {
            try {
                final String key = getCacheKey(activity.getId());
                final String value = objectMapper.writeValueAsString(activity);

                LOG.debug("write: key={}, value={}", key, value);
                redisTemplate.opsForValue().set(key, value);
            } catch (JsonProcessingException e) {
                LOG.warn("fail to convert json, id: {}", activity.getId());
            }
        }
    }

    public String getCacheKey(int activityId) {
        return getCachePrefix() + ":" + activityId;
    }
}
